package com.talkweb.baselibrary.banner.utils;

import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

public class ImageLoader {
    public static Image createImageView(Context context, String path) {
        Image imageView = new Image(context);
        TaskDispatcher refreshUITask = context.createParallelTaskDispatcher("", TaskPriority.HIGH);

        refreshUITask.syncDispatch(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(path);
                    URLConnection urlConnection = url.openConnection();
                    if (urlConnection instanceof HttpURLConnection) {
                        connection = (HttpURLConnection) urlConnection;
                    }
                    if (connection != null) {
                        connection.connect();
                        InputStream inputStream = urlConnection.getInputStream();
                        ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
                        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);

                        DirectionalLayout.LayoutConfig config = new DirectionalLayout.LayoutConfig(MATCH_PARENT, MATCH_PARENT);
                        imageView.setLayoutConfig(config);
                        imageView.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
                        imageView.setPixelMap(pixelMap);
                        pixelMap.release();
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        });
        return imageView;
    }
}